package com.jchen.system.controller;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import com.jchen.common.util.R;
import com.jchen.elasticsearch.dto.SysUserEsQueryDto;
import com.jchen.system.entity.SysUserEs;
import com.jchen.system.service.IUserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description es索引相关
 * @Author jchen
 * @Date 2023/12/21 15:19
 */
@Api(value = "ES",tags = "ES")
@RestController
@RequestMapping("/es")
public class ElasticSearchController {

    @Autowired
    private ElasticsearchClient elasticsearchClient;

    @Autowired
    private IUserInfoService userInfoService;

    /**
     * 创建索引
     * @return
     * @throws IOException
     */
    @GetMapping("createIndex")
    @ApiOperation("创建索引")
    public String createIndex() throws IOException {
        CreateIndexResponse createResponse = elasticsearchClient.indices().create(demo -> demo.index("demo1"));
        return Boolean.TRUE.equals(createResponse.acknowledged()) ? "创建成功" : "创建失败";
    }

    /**
     * 查询索引
     * @return
     * @throws IOException
     */
    @GetMapping("searchIndexList")
    @ApiOperation("查询索引")
    public String searchIndexList() throws IOException {
        GetIndexResponse getIndexResponse = elasticsearchClient.indices().get(demo -> demo.index("*"));
        return String.join(",", getIndexResponse.result().keySet());
    }

    /**
     * 删除索引
     * @return
     * @throws IOException
     */
    @GetMapping("deleteIndex")
    @ApiOperation("删除索引")
    public String deleteIndex() throws IOException {
        DeleteIndexResponse deleteIndexResponse = elasticsearchClient.indices().delete(demo -> demo.index("demo1"));
        return Boolean.TRUE.equals(deleteIndexResponse.acknowledged()) ? "删除成功" : "删除失败";
    }

    /**
     * 新建索引并插入数据
     * @return
     * @throws IOException
     */
    @GetMapping("initIndexAndInsert")
    @ApiOperation("新建索引并插入数据")
    public String initIndexAndInsert(SysUserEs sysUserEs) throws IOException {
        BooleanResponse booleanResponse = elasticsearchClient.indices().exists(demo1 -> demo1.index("demo1"));
        if (booleanResponse.value()) {
            elasticsearchClient.indices().delete(demo1 -> demo1.index("demo1"));
        }
        IndexResponse indexResponse = elasticsearchClient.index(demo1 -> demo1.index("demo1").document(sysUserEs));
        return indexResponse.result().jsonValue();
    }

    @GetMapping("insert")
    @ApiOperation("插入数据")
    public String insert(SysUserEs sysUserEs) throws IOException {
        IndexResponse indexResponse = elasticsearchClient.index(demo1 -> demo1.index("demo1").document(sysUserEs));
        return indexResponse.result().jsonValue();
    }

    @GetMapping("insertBatch")
    @ApiOperation("批量插入数据")
    public int insert(List<SysUserEs> sysUserEs) throws IOException {
        List<BulkOperation> bulkOperationArrayList = new ArrayList<>();
        //遍历添加到bulk中
        for(SysUserEs user : sysUserEs){
            bulkOperationArrayList.add(BulkOperation.of(o->o.index(i->i.document(user))));
        }
        BulkResponse bulkResponse = elasticsearchClient.bulk(b -> b.index("demo1").operations(bulkOperationArrayList));
        return bulkResponse.items().size();
    }

    @GetMapping("search")
    @ApiOperation("根据id查询数据")
    public String search(String id) throws IOException {
        GetResponse<SysUserEs> getResponse = elasticsearchClient.get(demo1 -> demo1.index("demo1").id(id), SysUserEs.class);
        return getResponse.source().toString();
    }

    @GetMapping("check")
    @ApiOperation("根据id判断数据是否存在")
    public String check(String id) throws IOException {
        BooleanResponse  getResponse = elasticsearchClient.exists(demo1 -> demo1.index("demo1").id(id));
        return getResponse.value()==true?"存在":"不存在";
    }

    @GetMapping("list")
    @ApiOperation("查询数据")
    public String list() throws IOException {
        SearchRequest searchRequest = new SearchRequest.Builder().index("demo1").build();
        SearchResponse<SysUserEs> getResponse = elasticsearchClient.search(searchRequest, SysUserEs.class);
        List<String> strList = new ArrayList<>();
        getResponse.hits().hits().stream().forEach(item -> {
            strList.add(item.source().toString());
        });
        return String.join(",", strList);
    }

    @GetMapping("listPageByEs/{pageNum}/{pageSize}")
    @ApiOperation("查询数据")
    public R listPageByEs(@PathVariable int pageNum, @PathVariable int pageSize, SysUserEsQueryDto dto) throws IOException {
        try {

            return R.ok(userInfoService.listPageByEs(pageNum,pageSize,dto));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.failed();
    }
}
